<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\grid\GridView;
use yii\helpers\Html;
use backend\models\Brand;
use backend\models\Factory;
use backend\models\GrpBrandHead;
use backend\models\BrandSearch;
use backend\models\BrandHead;
use yii\base\Object;
use yii\base\Response;
use yii\widgets\ActiveForm;
use backend\models\UploadForm;
use backend\models\Image;
use yii\web\UploadedFile;
/**
 * 品牌控制器
 * @author suiyue
 *
 */
class BrandController extends BaseController
{
	/**
	 * (non-PHPdoc)行为
	 * @see \yii\base\Component::behaviors()
	 */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * (non-PHPdoc)前置函数
     * @see \yii\web\Controller::beforeAction()
     */
    public function beforeAction($action)
    {
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	$action_list = array(
    			'index',
    	        'img-index',
    	        'head-img-index',
    			'update',
    	        'img-update',
    	        'head-img-update',
    			'view',
    	        'img-view',
    	        'head-img-view',
    			'create',
    			'upload',
    			'getname',
    	);
    	 $access=$this->checkAccess($action_list,$action);//判断操作的action是否在actionlist里面
    	 $this->beforeOp('brand', $access);//身份识别 权限验证  action验证
    	 return true;
    }
	/**
	 * 品牌列表列表
	 */
    public function actionIndex()
    {
    	$searchModel = new BrandSearch();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    	return $this->render('index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]);
    }
    
    /**
     * 品牌图片管理
     */
    public function actionImgIndex(){
        $searchModel = new BrandSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('imgindex', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 品牌类别图片管理
     */
    public function actionHeadImgIndex(){
        $searchModel = new BrandSearch();
        $dataProvider = $searchModel->headsearch(Yii::$app->request->queryParams);
        return $this->render('headimgindex', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 品牌名称唯一性
     */
    public function actionGetname(){
    	$model=new Brand();
    	$get=Yii::$app->request->get();
    	 $name=strval($get['name']);
    	 if($name==""||empty($name)){
    	 	echo 0;exit();
    	 }else{
    	 	$result=$model->CheckBrandByName($name);
    	 	if($result){
    	 		echo 2;exit();//存在
    	 	}else{
    	 		echo 1;exit();//不存在
    	 	}
    	 }
    }
    /**
     * 创建
     */
    public function actionCreate(){
    	$this->layout = 'main_small';
    	
    	$model = new Brand();
    	$factoryModel=new Factory();
    	
    	if ($model->load(Yii::$app->request->post())&&$model->validate()) {
    		//ajax验证
    		if(Yii::$app->request->isAjax){
    			Yii::$app->response->format=Response::FORMAT_JSON;
    			return ActiveForm::validate($model);
    		}
    		
    		//先验证品牌是否存在
    		$post=Yii::$app->request->post();
    		if(count($post)==0){
    			throw new ForbiddenHttpException(Yii::t('app','Sorry ,data is null!'));
    		}else{
    			//查询上一个品牌的厂家id 再+1判断工厂是否存在 不存在自己创建
    			$sql="SELECT factory_id FROM grp_brand ORDER BY id DESC LIMIT 1";
    			$brandList=Brand::findBySql($sql)->all();
    			$factory_idPrevfid=intval($brandList[0]['factory_id'])+1;
    			$checkFactory=$factoryModel->CheckFactory($factory_idPrevfid);
    			if($checkFactory){
    				$factory_id=$factory_idPrevfid;
    			}else{
    				//新增id
    				$factoryModel=new Factory();
    				$short_code=$factoryModel->getRandomStrNum();
    				while($factoryModel->CheckFactoryByCode($short_code)){
    					$short_code=$factoryModel->getRandomStrNum();
    					if(!$factoryModel->CheckFactoryByCode($short_code)){
    						break;
    					}
    				}
    				if($factoryModel->CheckFactoryByCode($short_code)){
    					$factoryModel->short_code=$short_code;
    				}else{
    					$short_code=$factoryModel->getRandomStrNum();
    					$factoryModel->short_code=$short_code;
    				}
    				//设置税率默认为1
    				if($factoryModel->insert()){
    					$factory_id=$factoryModel->id;
    				}else{
    					throw new ForbiddenHttpException(Yii::t('app','Sorry ,create factory is error!'));
    				}
    			}
    			if($factory_id){
    				//品牌状态
    				$usestatu=intval($post['Brand']['useing']);
    				if($usestatu==0){
    					$model->useing=1;
    				}
    				$model->factory_id=strval($factory_id);
    				$model->save();
    				//查询排序是否为空 
    				$brand=$model::findOne($model->id);
    				 $displayorder=intval($brand['order']);
    				if($displayorder==0){
    					$BrandModel= $this->findModel($model->id);
    					$BrandModel->order=$model->id;
    					$BrandModel->save();
    				}
    				return $this->redirect(['view', 'id' => $model->id]);
    			}else{
    				throw new ForbiddenHttpException(Yii::t('app','Sorry , factory_id is not exits!'));
    			}
    		}
    	}else{
    		//查询brand_head列表
    		return $this->render('create', [
    				'model' => $model,
    		]);
    	}
    	
    	
    }
    
    /**
     * 修改
     */
    public function actionUpdate($id){
    	$this->layout = 'main_small';
    	$model = $this->findModel($id);
    	$factoryModel=new Factory();
    	if ($model->load(Yii::$app->request->post())) {
    		//先验证品牌是否存在
    		$post=Yii::$app->request->post();
    		if(count($post)==0){
    			throw new ForbiddenHttpException(Yii::t('app','Sorry ,data is null!'));
    		}else{
    			$model->save();
    			return $this->redirect(['view', 'id' => $model->id]);
    		}
    	} else{
    		return $this->render('update', [
    			'model' => $model
    		]);
    	}
    }
   
    /**
     * 
     * @param   $id
     */
   public function actionImgUpdate($id){
       $this->layout = 'main_small';
        $model = $this->findModel($id);
        $oldImgid=intval($model->img_id);
      
        $Uploadmodel = new UploadForm();
       if ($model->load(Yii::$app->request->post())) {
           $Uploadmodel->scenario = 'no_need_file_name';
           $Uploadmodel->image_upload = UploadedFile::getInstance($model, 'img_id');
           if ($Uploadmodel->image_upload && $Uploadmodel->validate()) {
                  if($oldImgid==0){
                      $arr = Image::save_image_to_files($Uploadmodel,196,'品牌图片','item_default_image_thumb','item_default_image_small');
                      $model->img_id = $arr['img_url_id'];
                       $model->save();
                 }else{
                     $arr = Image::save_image_to_files($Uploadmodel,196,'品牌图片','item_default_image_thumb','item_default_image_small',$model->img_id,$model->img_id,$model->img_id);
                 }
               return $this->redirect(['img-view', 'id' => $model->id]);
           }else{
               return $this->redirect(['img-update', 'id' => $model->id]);
           }
           
       } else{
           $sql="select grp_brand.*,grp_brand_head.name grPBrandHead from grp_brand ,grp_brand_head
             where grp_brand.head_grp=grp_brand_head.id and grp_brand.id=:id";
           $param=array(":id"=>$id);
           $model=Brand::findBySql($sql,$param)->One();
           return $this->render('imgupdate', [
               'model' => $model
           ]);
       }
   }
   
   /**
    * 品牌分类图片修改
    * @param   $id
    * @return  
    */
   public function actionHeadImgUpdate($id){
       $this->layout = 'main_small';
       $model =BrandHead::findOne($id);
       $oldImgid=intval($model->img_id);
       if ($model->load(Yii::$app->request->post())) {
           //图片上传
           $Uploadmodel = new UploadForm();
           $Uploadmodel->scenario = 'no_need_file_name';
           $Uploadmodel->image_upload = UploadedFile::getInstance($model,'img_id');
           if ($Uploadmodel->image_upload && $Uploadmodel->validate()) {
               if($oldImgid==0){
                   $arr = Image::save_image_to_files($Uploadmodel,196,'品牌分类图片','item_default_image_thumb','item_default_image_small');
                   $model->img_id = $arr['img_url_id'];
                   $model->save();
               }else{
                   $arr = Image::save_image_to_files($Uploadmodel,196,'品牌分类图片','item_default_image_thumb','item_default_image_small',$model->img_id,$model->img_id,$model->img_id);
               }
               
               return $this->redirect(['head-img-view', 'id' => $model->id]);
           }else{
               return $this->redirect(['head-img-update', 'id' => $model->id]);
           }
           
       } else{
           $model=BrandHead::findOne($id);
           return $this->render('headimgupdate', [
               'model' => $model
           ]);
       }
   }
   
   /**
   
     * 
     * 测试
     * @param number $num
     */
    public function actionAddFactory($num=5){
    	
    	$factoryModel=new Factory();
    	for($i=0;$i<$num;$i++){
    		$short_code=$factoryModel->getRandomStrNum();
    		while($factoryModel->CheckFactoryByCode($short_code)){
    			$short_code=$factoryModel->getRandomStrNum();
    			if(!$factoryModel->CheckFactoryByCode($short_code)){
    				break;
    			}
    		}
    		if($factoryModel->CheckFactoryByCode($short_code)){
    			$factoryModel->short_code=$short_code;
    		}else{
    			$short_code=$factoryModel->getRandomStrNum();
    			$factoryModel->short_code=$short_code;
    		}
    		$factoryModel->insert();
    	}
    	
    }
    /**
     * 查看单条数据
     */
    public function actionView($id){
    	$this->layout = 'main_small';
    	$sql="select grp_brand.*,sys_image.url imgurl,grp_brand_head.name grPBrandHead
            from grp_brand left join sys_image on sys_image.id=grp_brand.img_id
            left join  grp_brand_head on grp_brand_head.id=grp_brand.head_grp
            where grp_brand.id=:id";
    	$param=array(":id"=>$id);
    	$model=Brand::findBySql($sql,$param)->one();
    	return $this->render('view', [
    			'model' => $model
    	]);
    }
    /**
     * 图片详情页
     * @param unknown $id
     * @return unknown
     */
    public function actionImgView($id){
        $this->layout = 'main_small';
        $sql="select grp_brand.*,sys_image.url imgurl,grp_brand_head.name grPBrandHead
            from grp_brand left join sys_image on sys_image.id=grp_brand.img_id  
            left join  grp_brand_head on grp_brand_head.id=grp_brand.head_grp
            where grp_brand.id=:id";
        $param=array(":id"=>$id);
        $model=Brand::findBySql($sql,$param)->one();
        //$model = Brand::findOne($id);
        return $this->render('imgview', [
            'model' => $model
        ]);
    }
    /**
     * 品牌分类详情页
     * @param unknown $id
     */
    public function actionHeadImgView($id){
        $this->layout = 'main_small';
        $sql="select  sys_image.url imgurl,grp_brand_head.*
            from grp_brand_head left join sys_image on sys_image.id=grp_brand_head.img_id
            where grp_brand_head.id=:id";
        $param=array(":id"=>$id);
        $model=Brand::findBySql($sql,$param)->one();
        return $this->render('headimgview', [
            'model' => $model
        ]);
    }
    /**
     * 查找单个
     * @param   $id
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = Brand::findOne($id)) !== null) {
        	$model = Brand::find()->where('id='.$id)->one();
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
   
    
}
